<?php
//
//	file: includes/calendar/birthday/class_calendar_birthday_ymd.php
//	author: ptirhiik
//	begin: 24/04/2006
//	version: 1.6.0 - 10/06/2006
//	license: http://opensource.org/licenses/gpl-license.php GNU General Public License (GPL)
//

if ( !defined('IN_PHPBB') )
{
	die('Hacking attempt');
}

// --------------
//
// birthday format is char(8), yyyymmdd (eg: 19700201)
//	empty can be NULL and ''
//
// --------------

class calendar_birthday_layer
{
	function read($user_fields, $xfrom, $xto)
	{
		global $db, $user;

		$data = array();

		$tac = $xto['y'] < 0 ? -1 : +1;
		$fac = $xfrom['y'] < 0 ? -1 : +1;
		$tm = $tac * ($xto['m'] - 1);
		$fm = $fac * ($xfrom['m'] - 1);
		$td = $tac * ($xto['d'] - 1);
		$fd = $fac * ($xfrom['d'] - 1);
		$delta = ($xto['y'] - $xfrom['y']) * 372 + ($tm - $fm) * 31 + ($td - $fd) - 1;
		if ( $delta < 0 )
		{
			return array();
		}
		$select = $delta < 372; // 31 * 12

		// no selection : get all birthday
		if ( !$select )
		{
			$sql = 'SELECT ' . implode(', ', $this->user_fields) . '
						FROM ' . USERS_TABLE . '
						WHERE user_id <> ' . ANONYMOUS . '
							AND user_active = 1
							AND user_birthday IS NOT NULL
							AND user_birthday <> \'\'
						ORDER BY username';
		}

		// select
		else
		{
			// we only consider the month and day
			$md_from = $this->md($xfrom);
			$md_to = $this->md($xto);

			// now we can read
			$sql = 'SELECT ' . implode(', ', $this->user_fields) . '
						FROM ' . USERS_TABLE . '
						WHERE user_id <> ' . ANONYMOUS . '
							AND user_active = 1
							AND user_birthday IS NOT NULL
							AND user_birthday <> \'\'
							AND (RIGHT(user_birthday, 4) >= \'' . $md_from . '\'' . ($md_from < $md_to ? ' AND ' : ' OR ') . 'RIGHT(user_birthday, 4) < \'' . $md_to . '\')
						ORDER BY username';
		}
		if ( !($result = $db->sql_query($sql, false, __LINE__, __FILE__)) )
		{
			message_die(GENERAL_ERROR, 'Could not read users data', '', __LINE__, __FILE__, $sql);
		}
		while ( $row = $db->sql_fetchrow($result) )
		{
			if ( $tdate = intval($row['user_birthday']) )
			{
				$bd = $tdate % 100;
				$tdate = intval($tdate / 100);
				$bm = $tdate % 100;
				$by = intval($tdate / 100);
				$row['user_birthday'] = array('m' => $bm, 'd' => $bd, 'y' => $by);
				$data[ intval($row['user_id']) ] = $row;
			}
		}
		$db->sql_freeresult($result);
		return $data;
	}

	function md($xtime)
	{
		return sprintf('%02d%02d', $xtime['m'], $xtime['d']);
	}
}

?>